package com.example.demo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {
    private static final long JWT_EXPIRATION_TIME = 60 * 60 * 1000;
    private static final String secretStr = "X48NAv7Cc+SfN5rxO13/NGFJy4JwNE3UFw6ZeQXfLh4=";
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr));
    /**
     * 生成 token
     */
    public static String genJwtToken(Map<String, Object> claim){
        String token = Jwts.builder().setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION_TIME))
                .signWith(key)
                .compact();

        return token;
    }

    /**
     * 校验 token
     */
    public static Claims parseToken(String token){
        JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try{
            claims = jwtParser.parseClaimsJws(token).getBody();
        }catch(Exception e) {
            log.error("token 解析失败，token: {}", token);
            return null;
        }
        return claims;
    }
}
